package tron

import (
	"fisherman/common/http"
	log "fisherman/common/logger"
	"fisherman/common/utils"
	"fisherman/main/cfg"
	"fmt"
	"github.com/tidwall/gjson"
	"strings"
	"time"
)

// 查询TRX余额
func QueryTRXBalance(address string) float64 {
	if len(address) != 34 {
		log.Errorf("QueryTRXBalance() address 地址格式错误：%s\n", address)
		return -1
	}
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/getaccount", map[string]any{"address": address, "visible": true})
	//log.Infof("getaccount:%s", rsp)
	return gjson.Get(rsp, "balance").Float() / 1e6
}

// TRX转账
func TransferTRX(fromAddr, fromAddrKey, toAddr string, amount float64) (txID, signedTxJson, log string, success bool) {
	log += fmt.Sprintf("%s 向 %s 转TRX：%v\n", fromAddr, toAddr, amount)
	if len(fromAddr) != 34 {
		log += fmt.Sprintf("TransferTRX() fromAddr 地址格式错误：%s\n", fromAddr)
		return
	}
	if len(toAddr) != 34 {
		log += fmt.Sprintf("TransferTRX() toAddr 地址格式错误：%s\n", toAddr)
		return
	}
	//创建交易
	data := map[string]any{
		"owner_address": fromAddr,
		"to_address":    toAddr,
		"amount":        int64(amount * 1e6),
		"visible":       true,
	}
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/createtransaction", data)
	if strings.Contains(rsp, "balance is not sufficient") {
		log += "TRX余额不足\n"
		return
	}

	//对交易进行签名
	signedTx, err := signTx(rsp, fromAddrKey)
	if err != nil {
		log += fmt.Sprintf("签名失败：%v\n", err)
		return
	}
	signedTxJsonBytes := utils.Map2Bytes(signedTx)
	signedTxJson = string(signedTxJsonBytes)
	txID = signedTx["txID"].(string)

	//广播交易
	if cfg.Config.RealTransfer {
		err = broadcastTx(signedTx)
		if err != nil {
			log += fmt.Sprintf("签名失败：%v\n", err)
			return
		}
		//查询订单是否完全成功
		for i := 0; i < 20; i++ {
			wait, queryErr := queryTransferResult(txID)
			if wait {
				time.Sleep(time.Millisecond * 500)
				continue
			}
			if queryErr != nil {
				log += fmt.Sprintf("执行 queryTransferResult(txID) 失败：%v\n", queryErr)
				return
			}
			break
		}
	} else {
		log += "未开启真实转账，跳过广播模拟成功\n"
	}
	success = true
	return
}
